<template>
  <!--text number password  textarea  inputNumber select datePicker timePicker dateTimePicker switch slider checkbox radio button-->

  <el-form :model="formObj" ref="formObj" :rules="rules" label-width="150px" class="form-con">
    <el-form-item v-for="(item,index) in formInfo" v-if="item.type !== 'button'" :key="index" :label="item.label" :prop="item.key">
      <el-input v-if="item.type === 'text' || item.type === 'number' || item.type === 'password' || item.type === 'textarea'"
                :type="item.type"
                :placeholder="item.placeholder"
                :clearable=item.clearable
                v-model="formObj[item.key]">
      </el-input>
      <el-input-number v-if="item.type === 'inputNumber'"
                       :min="item.min"
                       :max="item.max"
                       :step="item.step"
                       :precision="item.precision"
                       v-model="formObj[item.key]">
      </el-input-number>
      <el-select v-if="item.type === 'select' && item.dataSource"
                 v-model="formObj[item.key]"
                 :placeholder="item.placeholder">
        <el-option v-if="item.dataSource.length>0"
                   v-for="(option,index) in item.dataSource"
                   :key="index"
                   :label="option.label"
                   :value="option.value">
        </el-option>
      </el-select>
      <el-date-picker v-if="item.type==='datePicker'"
                      type="date"
                      :placeholder="item.placeholder"
                      v-model="formObj[item.key]">
      </el-date-picker>
      <el-date-picker v-if="item.type==='monthPicker'"
                      type="month"
                      :placeholder="item.placeholder"
                      v-model="formObj[item.key]">
      </el-date-picker>
      <el-date-picker v-if="item.type==='yearPicker'"
                      type="year"
                      :placeholder="item.placeholder"
                      v-model="formObj[item.key]">
      </el-date-picker>
      <el-time-picker v-if="item.type === 'timePicker'"
                      type="fixed-time"
                      :placeholder="item.placeholder"
                      v-model="formObj[item.key]">
      </el-time-picker>
      <el-date-picker v-if="item.type === 'dateTimePicker'"
                      type="datetime"
                      :placeholder="item.placeholder"
                      v-model="formObj[item.key]">
      </el-date-picker>
      <el-switch v-if="item.type === 'switch'"
                 v-model="formObj[item.key]">
      </el-switch>
      <el-slider v-if="item.type === 'slider'"
                 :min="item.min"
                 :max="item.max"
                 :step="item.step"
                 v-model="formObj[item.key]">
      </el-slider>
      <el-checkbox-group v-if="item.type === 'checkbox' && item.dataSource"
                         v-model="checkArr">
        <el-checkbox v-if="item.dataSource.length>0"
                     v-for="(option,index) in item.dataSource"
                     :key="index"
                     :label="option.value">
          {{option.label}}
        </el-checkbox>
      </el-checkbox-group>
      <el-radio-group v-if="item.type === 'radio' && item.dataSource"
                      v-model="formObj[item.key]">
        <el-radio v-if="item.dataSource.length>0"
                  v-for="(option,index) in item.dataSource"
                  :key="index"
                  :label="option.value">
          {{option.label}}
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">保存</el-button>
      <el-button type="danger" @click="onCancel">取消</el-button>
      <el-button v-for="(btn,index) in formInfo"
                 :key="index"
                 v-if="btn.type==='button'"
                 @click="btn.click"
                 :type="btn.status">
        {{btn.label}}
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  export default {
    name: "Form",
    props:{
      //表单各项配置
      formInfo:{
        type: Array,
        default: function () {
          return []
        }
      },
      //表单数据源
      formObj:{
        type: Object,
        default: function () {
          return {}
        }
      },
    },
    watch:{
      formInfo: {
        handler(newValue, oldValue) {
          this.formInfo=newValue;
          this.getRules();
        },
        deep: true
      }
    },
    data() {
      return {
        rules:this.getRules(),
        checkArr:this.getCheckedVal(), //复选框选中值
      }
    },
    created(){

    },
    methods:{
      getCheckedVal(){
        let checkVal = [];
        this.formInfo.map(item => {
          if(item.type === 'checkbox' && this.formObj[item.key]){
            checkVal = this.formObj[item.key];
          }
        });
        return checkVal
      },
      getRules(){
        let validatePhone=(rule, value, callback) =>{
          if(!/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/.test(value)){
            callback(new Error('请输入正确的手机号'));
          }else {
            callback();
          }
        };
        let validateInteger=(rule, value, callback) =>{
          if(!/^[0-9]\d*$/.test(value)){
            callback(new Error('请输入整型数据'));
          }else{
            callback();
          }
        };
        let validateFloat=(rule, value, callback) =>{
          if(!/^[0-9]\d*\.\d*|0\.\d*[0-9]\d*$/.test(value)){
            callback(new Error('请输入浮点型数据'));
          }else{
            callback();
          }
        };
        let validateIDCard=(rule, value, callback) =>{
          if(!/^[1-9]\d{5}[1-9]\d{3}((0[1-9])|(1[0-2]))((0[1-9])|([1-2]\d)|(3[0-1]))((\d{4})|(\d{3}[Xx]))$/.test(value)){
            callback(new Error('请输入正确的身份证号'));
          }else{
            callback();
          }
        };

        let ruleObj={};
        this.formInfo.map(form => {
          if(form.rule){
            let item = form.rule;
            ruleObj[form.key]={};
            if (item.required){
              ruleObj[form.key].required=true;
              // ruleObj[form.key].message='此选项不能为空';
            }
            if(item.type){
              ruleObj[form.key].type=item.type;
              ruleObj[form.key].trigger='blur';
              switch (item.type){
                case 'url' :
                  ruleObj[form.key].message='请输入正确的url地址';
                  break;
                case 'email' :
                  ruleObj[form.key].message='请输入正确的email地址';
                  break;
                case 'phone' :
                  ruleObj[form.key].type='number';
                  ruleObj[form.key].validator=validatePhone;
                  break;
                case 'integer' :
                  ruleObj[form.key].type='number';
                  ruleObj[form.key].validator=validateInteger;
                  break;
                case 'float' :
                  ruleObj[form.key].type='number';
                  ruleObj[form.key].validator=validateFloat;
                  break;
                case 'IDCard' :
                  ruleObj[form.key].validator=validateIDCard;
                  break;
              }
            }
            if (!ruleObj[form.key].trigger)
              ruleObj[form.key].trigger='change';
          }
        });
        return ruleObj;
      },
      onSubmit(){
        console.log("from index ..................")
        this.formInfo.map(item => {
          if(item.type === 'checkbox')
            this.formObj[item.key] = this.checkArr;
        });
        this.$refs['formObj'].validate((valid) => {
          if (valid) {
            this.$emit('formDataSave',this.formObj)
          } else {
            this.$message.warning('校验未通过');
          }
        });
      },
      onCancel(){
        this.$emit("formOptionCancel", null);
      }
    }
  }
</script>

<style scoped>
.form-con{
  width: 100%;
  padding: 16px 0;
  margin: 0 auto;
}
</style>
